import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:permission_handler/permission_handler.dart';
import 'dart:typed_data';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

List<Widget> movableItems = [];

class EditPage extends StatefulWidget {
  EditPage({Key key, this.templateIndex}) : super(key: key);
  _EditPageState createState() => _EditPageState();
  final int templateIndex;
  double gWidth;
  double gHeight;
}

class _EditPageState extends State<EditPage> {
  File _image1;
  File _image2;
  File _image3;
  File _image4;

  GlobalKey globalKey = GlobalKey();

  void initState() {
    super.initState();
    var permission =
        PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    print("permission status is " + permission.toString());
    PermissionHandler().requestPermissions(<PermissionGroup>[
      PermissionGroup.storage, // 在这里添加需要的权限
    ]);
  }

  final picker = ImagePicker();
  Future getImage(int index) async {
    print("getImage ");
    FocusScope.of(context).requestFocus(FocusNode());

    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      if (pickedFile != null) {
        switch (index) {
          case 1:
            _image1 = File(pickedFile.path);
            break;
          case 2:
            _image2 = File(pickedFile.path);
            break;
          case 3:
            _image3 = File(pickedFile.path);
            break;
          case 4:
            _image4 = File(pickedFile.path);
            break;
        }

        print('image selected:' + pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

  Future saveImage() async {
    BuildContext buildContext = globalKey.currentContext;
    if (null != buildContext) {
      RenderRepaintBoundary boundary = buildContext.findRenderObject();
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      print("保存" + result.toString());
      if (result.toString().isNotEmpty) {
        Fluttertoast.showToast(
          msg: '保存成功',
          fontSize: 14,
          gravity: ToastGravity.CENTER,
          timeInSecForIos: 1,
          textColor: Colors.white,
        );
      } else {
        Fluttertoast.showToast(
          msg: '保存失败',
          fontSize: 14,
          gravity: ToastGravity.CENTER,
          timeInSecForIos: 1,
          textColor: Colors.white,
        );
      }
    }
  }

  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    widget.gWidth = size.width;
    widget.gHeight = size.height;

    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            icon: Icon(Icons.save),
            onPressed: () {
              print("保存");
              saveImage();
            },
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: RepaintBoundary(//用于截图
          key: globalKey,
          child:Container(
            color: Colors.white,
            height: widget.gWidth ,
            child: Stack(
              children: <Widget>[
                _buildTemplate(widget.templateIndex),
                Stack(
                  children: movableItems,
                ),
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.text_format),
        onPressed: () {
          print('FloatingActionButton');
          setState(() {
            var moveItem = MoveableStackItem(
              delete: () {
                setState(() {
                  print('item delete');
                });
              },
            );
            movableItems.add(moveItem);
          });
        },
      ),//添加文字
    );
  }

  Widget _buildTemplate(int index) {
    var curWidget;
    switch (index) {
      case 0:
        curWidget = _buildFour();
        break;
    }
    return curWidget;
  }

  Widget _buildFour() {
    return GridView.count(
      //水平子Widget之间间距
      crossAxisSpacing: 0.0,
      //垂直子Widget之间间距
      mainAxisSpacing: 0.0,
      //GridView内边距
      padding: EdgeInsets.all(15.0),
      //一行的Widget数量
      crossAxisCount: 2,

      //子Widget宽高比例
      childAspectRatio: 1.0,
      //子Widget列表
      children: <Widget>[
        Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5),
              color: Color.fromRGBO(0, 0, 0, 240),
              width: widget.gWidth / 2 - 30,
              height: widget.gWidth / 2 - 5,
              child: _image1 == null
                  ? IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        getImage(1);
                      },
                    )
                  : ClipRect(
                      child: PhotoView(
                        imageProvider: FileImage(_image1),
                        maxScale: PhotoViewComputedScale.covered * 2.0,
                        minScale: PhotoViewComputedScale.contained * 0.8,
                        initialScale: PhotoViewComputedScale.covered,
                      ),
                    ),
            ),
            IconButton(
              icon: Icon(
                Icons.redo,
                color: Colors.orange,
              ),
              onPressed: () {
                setState(() {
                  _image1 = null;
                });
              },
            ),
            Positioned(
                left: 20,
                top: 15,
                child: Text(
                  '1',
                  style: new TextStyle(
                    color: Color.fromARGB(255, 255, 255, 255),
                    fontSize: 30.0,
                  ),
                )),
          ],
        ),
        Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5),
              color: Color.fromRGBO(0, 0, 0, 240),
              width: widget.gWidth / 2 - 30,
              height: widget.gWidth / 2 - 5,
              child: _image2 == null
                  ? IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        getImage(2);
                      },
                    )
                  : ClipRect(
                      child: PhotoView(
                        imageProvider: FileImage(_image2),
                        maxScale: PhotoViewComputedScale.covered * 2.0,
                        minScale: PhotoViewComputedScale.contained * 0.8,
                        initialScale: PhotoViewComputedScale.covered,
                      ),
                    ),
            ),
            IconButton(
              icon: Icon(
                Icons.redo,
                color: Colors.orange,
              ),
              onPressed: () {
                setState(() {
                  _image2 = null;
                });
              },
            ),
            Positioned(
                left: 20,
                top: 15,
                child: Text(
                  '2',
                  style: new TextStyle(
                    color: Color.fromARGB(255, 255, 255, 255),
                    fontSize: 30.0,
                  ),
                )),
          ],
        ),
        Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5),
              color: Color.fromRGBO(0, 0, 0, 240),
              width: widget.gWidth / 2 - 30,
              height: widget.gWidth / 2 - 5,
              child: _image3 == null
                  ? IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        getImage(3);
                      },
                    )
                  : ClipRect(
                      child: PhotoView(
                        imageProvider: FileImage(_image3),
                        maxScale: PhotoViewComputedScale.covered * 2.0,
                        minScale: PhotoViewComputedScale.contained * 0.8,
                        initialScale: PhotoViewComputedScale.covered,
                      ),
                    ),
            ),
            IconButton(
              icon: Icon(
                Icons.redo,
                color: Colors.orange,
              ),
              onPressed: () {
                setState(() {
                  _image3 = null;
                });
              },
            ),
            Positioned(
                left: 20,
                top: 15,
                child: Text(
                  '3',
                  style: new TextStyle(
                    color: Color.fromARGB(255, 255, 255, 255),
                    fontSize: 30.0,
                  ),
                )),
          ],
        ),
        Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5),
              color: Color.fromRGBO(0, 0, 0, 240),
              width: widget.gWidth / 2 - 30,
              height: widget.gWidth / 2 - 5,
              child: _image4 == null
                  ? IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        getImage(4);
                      },
                    )
                  : ClipRect(
                      child: PhotoView(
                        imageProvider: FileImage(_image4),
                        maxScale: PhotoViewComputedScale.covered * 2.0,
                        minScale: PhotoViewComputedScale.contained * 0.8,
                        initialScale: PhotoViewComputedScale.covered,
                      ),
                    ),
            ),
            IconButton(
              icon: Icon(
                Icons.redo,
                color: Colors.orange,
              ),
              onPressed: () {
                setState(() {
                  _image4 = null;
                });
              },
            ),
            Positioned(
                left: 20,
                top: 15,
                child: Text(
                  '4',
                  style: new TextStyle(
                    color: Color.fromARGB(255, 255, 255, 255),
                    fontSize: 30.0,
                  ),
                )),
          ],
        ),
      ],
    );
  }
}

class MoveableStackItem extends StatefulWidget {
  Function delete; // 点击删除按钮时的回调

  MoveableStackItem({Key key, this.delete}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _MoveableStackItemState();
  }
}

class _MoveableStackItemState extends State<MoveableStackItem> {
  double xPosition = 50;
  double yPosition = 50;
  Color color;
  bool closeBtnVisible=false;
  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    color = Colors.blue;

    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        // TextField has lost focus
        print('lost');
        closeBtnVisible=true;
      }else{
        print('get');
        closeBtnVisible=false;
      }
      setState(() {

      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: yPosition,
      left: xPosition,
      child: GestureDetector(
        onPanUpdate: (tapInfo) {
          setState(() {
            xPosition += tapInfo.delta.dx;
            yPosition += tapInfo.delta.dy;
          });
        },
        child: Stack(children: <Widget>[
          FitTextField(focusNode: _focusNode,),
          Positioned(
            top: 0,
            left: 0,
            child: Offstage(
              offstage: closeBtnVisible,
              child:  IconButton(
                  icon: Icon(
                    Icons.close,
                    color: Colors.red,
                  ),
                  onPressed: () {
                    movableItems.remove(this.widget);
                    widget.delete();
                  }),
            ),

          ),
        ]),
      ),
    );
  }
}

class FitTextField extends StatefulWidget {
  final String initialValue;
  final double minWidth;
  final double minHeight;
  final FocusNode focusNode;
  const FitTextField(
      {Key key, this.focusNode,this.initialValue, this.minWidth: 60, this.minHeight: 18})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => new FitTextFieldState();
}

class FitTextFieldState extends State<FitTextField> {
  TextEditingController txt = TextEditingController();
  TextStyle textStyle = TextStyle(color: Colors.black,fontSize: 10);

  initState() {
    super.initState();
    txt.text = widget.initialValue;
  }

  @override
  Widget build(BuildContext context) {
    TextSpan ts = new TextSpan(style: textStyle, text: txt.text);
    TextPainter tp =
        new TextPainter(text: ts, textDirection: TextDirection.ltr);
    tp.layout();
    var textWidth = tp.width *
        1.2; // We will use this width for the container wrapping our TextField
    var textHeight = tp.height + 20;

    // Enforce a minimum width
    if (textWidth < widget.minWidth) {
      textWidth = widget.minWidth;
    }
    if (textHeight < widget.minHeight) {
      textHeight = widget.minHeight;
    }
    return Padding(
        padding: EdgeInsets.all(25),
        child:  Container(
          width: textWidth,
          height: textHeight,
          //color: Colors.white,
          decoration: new BoxDecoration(
            color: Color.fromARGB(200, 255, 255, 255),
            border: Border.all(color: Colors.grey, width: 0.5), //边框
            borderRadius: BorderRadius.all(
              //圆角
              Radius.circular(textHeight/3.5),
            ),
          ),
          child: TextField(
            autofocus: true,
            focusNode: widget.focusNode,
            keyboardType: TextInputType.multiline,
            maxLines: 100, //不限制行数
            textAlign: TextAlign.center,
            style: textStyle,
            controller: txt,
            decoration: InputDecoration(
              //contentPadding:EdgeInsets.all(10),
              isDense: true,
              border: InputBorder.none,
              hintText: '说点啥...',
              labelStyle: TextStyle(
                color: Colors.black,
              ),
            ),
            onChanged: (text) {
              setState(() {});
            },
          ),
        )
    );
  }
}
